package com.lagou.dubbo.filter;

import com.lagou.dubbo.util.IpUtil;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * description: ip透传
 *
 * @param
 * @author yangkailan
 * date 2020/9/8 下午10:57
 * @return
 */
@Activate(group = {CommonConstants.CONSUMER})
public class TransportIPFilter implements Filter {

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        long   startTime  = System.currentTimeMillis();
        try {
//            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
//                    .getRequestAttributes()).getRequest();
            String requestIp = RpcContext.getContext().getRemoteHost();
            RpcContext.getContext().setAttachment("ip",requestIp);

           return invoker.invoke(invocation);
        } finally {
            System.out.println("invoke time:"+(System.currentTimeMillis()-startTime) + "毫秒");
        }
    }
}
